﻿using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Management.Automation;

namespace DeployTools
{
  [Cmdlet(VerbsLifecycle.Invoke, "MSBuild")]
  public class InvokeMSBuild : PSCmdlet
  {
    [Parameter(Mandatory = true)]
    public string MSBuildArguments { get; set; }

    private string MSBuildToolsPath { get; set; }

    protected override void BeginProcessing()
    {
      RegistryKey key;
      string latestVersion = "";
      decimal latest = 0;
      decimal current;
      string toolPath;

      using (key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\MSBuild\ToolsVersions"))
      {
        if (key != null)
        {
          foreach (string version in key.GetSubKeyNames())
          {
            if (decimal.TryParse(version, NumberStyles.Number, CultureInfo.InvariantCulture, out current))
            {
              if (current > latest)
              {
                latest = current;
                latestVersion = version;
              }
            }
          }
        }
        else
        {
          throw new Exception("MSBuild not found. 1");
        }
      }

      if (latest > 0)
      {
        using (key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\MSBuild\ToolsVersions\" + latestVersion))
        {
          if (key != null)
          {
            toolPath = key.GetValue("MSBuildToolsPath") as string;
            if (toolPath != null)
            {
              this.MSBuildToolsPath = toolPath;
            }
            else
            {
              throw new Exception("MSBuild not found. 2");
            }
          }
          else
          {
            throw new Exception("MSBuild not found. 3");
          }
        }
      }
      else
      {
        throw new Exception("MSBuild not found. 4");
      }
    }

    protected override void ProcessRecord()
    {
      ProcessStartInfo psInfo;
      Process proc;

      psInfo = new ProcessStartInfo()
      {
        Arguments = this.MSBuildArguments,
        RedirectStandardError = false,
        RedirectStandardOutput = false,
        UseShellExecute = true,
        FileName = Path.Combine(this.MSBuildToolsPath, "MSBuild.exe")
      };

      using (proc = new Process() { StartInfo = psInfo })
      {
        proc.Start();
        proc.WaitForExit();
        WriteObject(proc.ExitCode);
      }
    }
  }
}
